<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/7/3
 * Time: 20:22
 */

namespace Api\Controller;


use Api\Vendor\BoyeUtils\BoyeUtils;
use OAuth2Manage\Api\AccessTokensApi;
use Think\Controller\RestController;
use Admin\Api\ConfigApi;

/**
 * 接口基类
 * Class ApiController
 *
 * @author 老胖子-何必都 <hebiduhebi@126.com>
 * @package Api\Controller
 */
abstract class ApiController extends RestController{

    protected $encrypt_key = "";
    protected $client_id = "";
    protected $notify_id;

    protected $allow_controller = array('token','file','alipayapp','alipayrefund','wxpayapp');

    /**
     * 构造函数
     */
    public function __construct(){
        parent::__construct();
        header("X-Copyright:http://www.itboye.com");
        
        if(!defined("CONTROLLER_NAME") || ( !in_array(strtolower(CONTROLLER_NAME),$this->allow_controller) &&  strtolower(CONTROLLER_NAME) != "index" )){
            $this->apiReturnErr("1002","请求资源不存在!");
        }

        if(method_exists($this,"_init")){
            $this->_init();
        }
    }





    public function _empty(){
        $this->apiReturnErr("访问地址错误","404");
    }

    /**
     * Ajax方式返回数据到客户端
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type AJAX返回数据格式
     * @param int $json_option 传递给json_encode的option参数
     * @return void
     */
    protected function ajaxReturn($data,$type='',$json_option=0) {
        $code = $data['code'];
        if($code == 0){
            $type = "T";
        }else{
            $type = "F";
        }

        $data = BoyeUtils::encrypt($data);
        $now = time();

        $param = array(
            'client_id'=>$this->client_id,
            'data'=>$data,
            'notify_id'=>$this->notify_id,
            'time'=>strval($now),
            'type'=>$type,
            'alg'=>'md5',
        );

        $param['sign'] = BoyeUtils::sign($param);

        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode($param,$json_option));
    }
    /**
     * ajax返回
     * @param $data
     * @internal param $i
     */
    protected function apiReturnSuc($data){
        $this->ajaxReturn(array('code'=>0,'data'=>$data,'notify_id'=>$this->notify_id),"json");
    }

    /**
     * ajax返回，并自动写入token返回
     * @param $data
     * @param int $code
     * @internal param $i
     */
    protected function apiReturnErr($data,$code=-1){
        $this->ajaxReturn(array('code'=>$code,'data'=>$data,'notify_id'=>$this->notify_id),"json");
    }

    /**
     * @param $key
     * @param string $default
     * @param string $emptyErrMsg  为空时的报错
     * @return mixed
     */
    public function _post($key,$default='',$emptyErrMsg=''){
        $value = I("post.".$key,$default);

        if($default == $value && !empty($emptyErrMsg)){
            $this->apiReturnErr($emptyErrMsg);
        }
        return $value;
    }

    /**
     * @param $key
     * @param string $default
     * @param string $emptyErrMsg  为空时的报错
     * @return mixed
     */
    public function _get($key,$default='',$emptyErrMsg=''){
        $value = I("get.".$key,$default);

        if($default == $value && !empty($emptyErrMsg)){
            $this->apiReturnErr($emptyErrMsg);
        }
        return $value;
    }

    /**
     * 从数据库中取得配置信息
     */
    protected function getConfig() {
        $config = S('global_config');
        //dump($config);
        if ($config === false) {
            $map = array();
            $fields = 'type,name,value';
            $result = apiCall(ConfigApi::QUERY_NO_PAGING, array($map, false, $fields));
            if ($result['status']) {
                $config = array();

                if (is_array($result['info'])) {
                    foreach ($result['info'] as $value) {
                        $config[$value['name']] = $this -> parse($value['type'], $value['value']);

                    }
                }
                //缓存配置300秒
                S("global_config", $config, 300);
            } else {
                LogRecord('INFO:' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
                $this -> error($result['info']);
            }
        }

        C($config);
    }

    /**
     * 根据配置类型解析配置
     * @param  integer $type 配置类型
     * @param  string $value 配置值
     * @return array|string
     */
    private static function parse($type, $value) {
        switch ($type) {
            case 3 :
                //解析数组
                $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
                if (strpos($value, ':')) {
                    $value = array();
                    foreach ($array as $val) {
                        list($k, $v) = explode(':', $val,2);
                        $value[$k] = $v;
                    }
                } else {
                    $value = $array;
                }
                break;
        }
        return $value;
    }

    /**
     *
     * @param $result
     * @param bool $cantBeNull
     * @param string $whenNullMsg 当为空时的信息
     */
    protected function checkApiCallResult($result,$cantBeNull=true,$whenNullMsg="获取信息为空!"){

        if(!$result['status']){
            $this->apiReturnErr($result['info']);
        }
        
        if($cantBeNull && is_null($result['info'])){
            $this->apiReturnErr($whenNullMsg);
        }

    }



}